// 导入路径辅助模块，避免重复引用
const pathImport = require('../helpers/path_import.js');
const { pageHelper, cloudHelper, validate } = pathImport;;
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { sampleStore } = require('../../../config/store_config.js');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		// 仅保留UI配置相关的本地状态
		// 业务数据从store中获取
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		ProjectBiz.initPage(this);
		
		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: sampleStore,
			fields: [
				'formData',
				'options',
				'loading',
				'canAdd'
			],
			actions: [
				'resetFormData',
				'setFormField', 
				'setStatusIndex',
				'setProjectIndex',
				'loadOptions',
				'addAttachments',
				'removeAttachment',
				'submitSampleAdd',
				'checkAddPermission'
			]
		});
		
		// 重置表单数据
		this.resetFormData();
		
		// 加载选项
		await this.loadOptions();
		
		// 检查权限
		await this.checkAddPermission();
	},
	
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function() {
		// 销毁绑定
		if (this.storeBindings) {
			this.storeBindings.destroyStoreBindings();
		}
	},

	/**
	 * 状态选择
	 */
	bindStatusChange: function(e) {
		let index = Number(e.detail.value);
		if (index >= 0 && index < this.data.options.statusOptions.length) {
			this.setStatusIndex(index);
		}
	},

	/**
	 * 项目选择
	 */
	bindProjectChange: function(e) {
		let index = Number(e.detail.value);
		this.setProjectIndex(index);
	},

	/**
	 * 表单输入
	 */
	bindInput: function(e) {
		let field = e.currentTarget.dataset.field;
		let value = e.detail.value;
		this.setFormField(field, value);
	},

	/**
	 * 选择图片
	 */
	bindChooseImageTap: async function() {
		try {
			let res = await wx.chooseMedia({
				count: 9,
				mediaType: ['image'],
				sizeType: ['compressed']
			});

			wx.showLoading({
				title: '上传中...',
				mask: true
			});

			await this.addAttachments(res.tempFiles);
			
			wx.hideLoading();
		} catch (err) {
			console.error('选择或上传图片失败:', err);
			wx.hideLoading();
			pageHelper.showModal('选择图片失败，请重试');
		}
	},

	/**
	 * 删除图片
	 */
	bindDelImageTap: function(e) {
		let index = e.currentTarget.dataset.index;
		this.removeAttachment(index);
	},

	/**
	 * 预览图片
	 */
	previewImage: function(e) {
		let url = e.currentTarget.dataset.url;
		if (!url) return;

		let urls = this.data.formData.SAMPLE_ATTACHMENTS;
		wx.previewImage({
			current: url,
			urls
		});
	},

	/**
	 * 取消
	 */
	bindCancelTap: function() {
		wx.navigateBack();
	},

	/**
	 * 表单提交
	 */
	bindFormSubmit: async function () {
		try {
			// 表单验证
			const rules = [
				{ fields: ['formData.SAMPLE_CODE'], name: '存样编号', required: true },
				{ fields: ['formData.SAMPLE_NAME'], name: '样品名称', required: true },
			];
			
			// 进行表单验证
			const checkRes = pageHelper.formVerify(this.data, rules);
			if (!checkRes) return;
			
			const callback = async () => {
				try {
					const result = await this.submitSampleAdd();
					
					if (result) {
						pageHelper.showSuccessToast('添加成功', 1500);
						setTimeout(() => {
							wx.navigateBack();
						}, 1500);
					}
				} catch (err) {
					console.error(err);
					pageHelper.showModal('添加失败，请重试');
				}
			};
			
			pageHelper.showConfirm('确认提交?', callback);
		} catch (err) {
			console.error(err);
		}
	}
}); 